package com.nazca.tvremote.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.View;
import android.widget.ImageButton;

import com.nazca.tvremote.R;
import com.nazca.tvremote.event.RemoteSensorEvent;
import com.nazca.tvremote.service.Controller;
import com.nazca.tvremote.util.RLog;
import com.nazca.tvremote.util.Settings;
import com.nazca.tvremote.view.TitleBar;

public class GestureRemoteActivity extends Activity implements SensorEventListener{
	
	private static final String TAG = "GestureRemoteActivity";
	
	private static final float[] GESTURE_REMOTE_SPEED_VALUES = new float[]{
		0.25f, 0.5f, 1f, 1.5f, 2
	};
	
	private TitleBar mTitleBar;
	
	private ImageButton mButton;
	
	private SensorManager mSensorManager;
//	private Settings mSettings;
	private int mGestureRemoteSpeedKey;
	private float mGestureRemoteSpeedValue;
	private Controller mController;
	
	private WakeLock mWakeLock = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.gesture_remote);
		
		mTitleBar = (TitleBar) findViewById(R.id.title_bar);
		mTitleBar.getBackButton().setText(R.string.main_gesture_remote);
		mTitleBar.getBackButton().setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				finish();
			}
		});
		
		mButton = (ImageButton) findViewById(R.id.setting);
		
		mButton.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
			}
		});
		
		mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		mController = Controller.getInstance(getApplication());
		Sensor sensorAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (sensorAccelerometer != null) {
            mSensorManager.registerListener(this, sensorAccelerometer, SensorManager.SENSOR_DELAY_UI);
//            mSensorManager.registerListener(this, sensorAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
        }
        
        mIsSendFinished = true;
        
        Settings settings = Settings.getSettings(this);
        mGestureRemoteSpeedKey = settings.mGestureRemoteSpeed;
        mGestureRemoteSpeedValue = GESTURE_REMOTE_SPEED_VALUES[mGestureRemoteSpeedKey];
        
        acquireWakeLock();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		mSensorManager.unregisterListener(this);
		releaseWakeLock();

		mIsSendFinished = false;
        mHandler.removeMessages(0);
	}
	
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		RLog.d(TAG, "onSensorChanged()");
		
		float values[] = event.values;
//		long timestamp = event.timestamp;
//		int accuracy = event.accuracy;
		
//		Sensor sensor = event.sensor;
//		Log.d(TAG, "type:" + sensor.getType());
		RLog.d(TAG, "[x,y,z]:" + "[" + values[0] + "," + values[1] + "," + values[2] + "]");

		values[0] = values[0] * mGestureRemoteSpeedValue;
		values[1] = values[1] * mGestureRemoteSpeedValue;
		values[2] = values[2] * mGestureRemoteSpeedValue;
		RLog.d(TAG, "[x,y,z]:" + "[" + values[0] + "," + values[1] + "," + values[2] + "]");
		
		//Limit 0-10?

		if (mIsSendFinished){
		    mHandler.sendMessageDelayed(Message.obtain(mHandler, 0, event), 100);
		    mIsSendFinished = false;
		}
	}
    
    private boolean mIsSendFinished = true;
    
	private Handler mHandler = new Handler(){
	    public void handleMessage(android.os.Message msg) {
	        
	        RemoteSensorEvent sensorEvent = new RemoteSensorEvent((SensorEvent)msg.obj);
	        mController.println(sensorEvent.toString());
	        RLog.d(TAG, "send sensor event: "+sensorEvent);
	        
	        mIsSendFinished = true;
	    };
	};
    
	private void acquireWakeLock() {
		if (mWakeLock == null) {
			PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
//			mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MAIL_SERVICE");
			mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this.getClass().getCanonicalName());
			mWakeLock.acquire();
		}
	}
	
	private void releaseWakeLock() {
		if (mWakeLock != null && mWakeLock.isHeld()) {
			mWakeLock.release();
			mWakeLock = null;
		}
	}
}